package com.ljy.jymail.client1.controller;

import com.sun.deploy.net.HttpUtils;
import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {

    public static int LargeNum = 1024*1024*1024*50;

    @Value("${sso.server.url}")
    String ssoServerUrl;

    @Value("${server.port}")
    String port;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    //无需登录就可以访问
    @ResponseBody
    @GetMapping("/hello")
    public String Hello(){
        return "hello";
    }



    //需要登陆才能访问
    @GetMapping("/employees")
    public String employees(Model model, HttpServletRequest request, HttpSession session, @RequestParam(required = false,name = "token") String token){
        if (!StringUtils.isEmpty(token)){
            String s = stringRedisTemplate.opsForValue().get(token);
            session.setAttribute("loginUser",s);
            //TODO:去ssoserver获取token对应的真正信息
            //使用spring的restTemplate发送请求查询信息
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8085/userInfo?token=" + s, String.class);
            //获取响应的值
            String body = forEntity.getBody();
            session.setAttribute("loginUser",body);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            //没登录,跳转到登录服务器进行登录
            return "redirect:"+ssoServerUrl+"?redirect_url=http://"+request.getServerName()+":"+port+"/employees";
        }else {
            List<String> emps = new ArrayList<>();
            emps.add("张三");
            emps.add("李四");
            emps.add("王五");
            emps.add("赵六");
            emps.add("孙七");
            model.addAttribute("emps",emps);
            return "list";
        }
    }

    @GetMapping("/")
    @ResponseBody
    public String index(){
        return "index";
    }
}
